﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Collections.ObjectModel;
using System.Data.Objects;
using System.Data;
using CCF20Model.ModelBase;
namespace CCF20Model
{
    public class VehicleMaintenanceCollection : ObservableCollection<VehicleMaintenanceRecord>
    {
        private CCF20Entities ccf20Entities;
        private int vehicleID;

        protected override void InsertItem(int index, VehicleMaintenanceRecord item)
        {
            if (item == null) return;
            item.IsActive = true;
            item.VehicleID = vehicleID;
            //item.Context = ccf20Entities;
            ccf20Entities.VehicleMaintenanceRecords.AddObject(item);
            //ccf20Entities.SaveChanges();
            base.InsertItem(index, item);
        }

        protected override void RemoveItem(int index)
        {
            ccf20Entities.VehicleMaintenanceRecords.DeleteObject(this[index]);
            //ccf20Entities.SaveChanges();
            base.RemoveItem(index);
        }
        public VehicleMaintenanceCollection(IEnumerable<VehicleMaintenanceRecord> maintenances, CCF20Entities context,Vehicle vehicle)
            : base(maintenances)
        {
            ccf20Entities = context;
            vehicleID = vehicle.VehicleID;
        }

    }
    public class CombinedMaintenanceType0
    {
        public MaintenanceType MaintenanceType { set; get; }
        public VehicleMaintenanceRecord MaintenaceRecord { set; get; }
        public int? ServiceMileage { set; get; }
        public int? ServicePeriod { set; get; }
        public bool IsRecord { set; get; }
        public bool IsHistory { set; get; }
    }
    public class CombinedMaintenanceType
    {
        public MaintenanceType MaintenanceType {set;get;}
        public VehicleMaintenanceRecord MaintenaceRecord { set; get; }
        public int? ServiceMileage { set; get; }
        public int? ServicePeriod { set; get; }
        public bool IsRecord { set; get; }
        public bool IsHistory { set; get; }
    }
    public class VehicleMaintenanceModel : ModelBaseClass
    {
        public VehicleMaintenanceModel(CCF20Entities ccf20Ent)
            : base(ccf20Ent)
        {
            
        }
        public MaintenanceType GetMaintenanceType(int MaintenanceTypeID)
        {
            return ccf20Entities.MaintenanceTypes.Where(m => m.MaintenanceTypeID == MaintenanceTypeID).FirstOrDefault();
        }
        public VehicleMaintenanceCollection GetVehicleMaintenanceRecord(Vehicle vehicle)
        {
            if (vehicle == null) return null;
            
            var query = from f in ccf20Entities.VehicleMaintenanceRecords
                        where f.VehicleID == vehicle.VehicleID &&
                              f.IsActive
                        select f;
            //ccf20Entities.Refresh(RefreshMode.StoreWins, query);
            return new VehicleMaintenanceCollection(query, this.ccf20Entities,vehicle);
        }
        public IQueryable<CombinedMaintenanceType> GetCombinedMaintenanceTypeByVehicle(Vehicle vehicle)
        {
            Vehicle myVehicle = ccf20Entities.Vehicles.Where(
                                    v => v.VehicleID == vehicle.VehicleID)
                                    .FirstOrDefault();

            var query = from m in ccf20Entities.MaintenanceTypes
                           where m.VehicleTypeID == myVehicle.VehicleTypeID
                           join r in
                               (from vm in ccf20Entities.VehicleMaintenanceRecords
                                where vm.VehicleID == vehicle.VehicleID
                                select vm)
                           on m.MaintenanceTypeID equals r.MaintenanceTypeID into joinedMaintenanceType
                           from maintenance in joinedMaintenanceType.DefaultIfEmpty()
                           orderby m.Name, m.Priority
                           select new CombinedMaintenanceType0
                           {
                               MaintenanceType = m,
                               MaintenaceRecord = maintenance,
                               IsRecord = maintenance != null ? true : false,
                               ServiceMileage = maintenance != null ? maintenance.ServiceMileage : m.ServiceMileage,
                               ServicePeriod = maintenance != null ? maintenance.ServicePeriod : m.ServicePeriod
                           };

            var query2 = from m in query
                         join r in
                               (from vm in ccf20Entities.VehicleMaintenanceHistories
                                where vm.VehicleID == vehicle.VehicleID && vm.IsActive == true
                                select vm)
                         on m.MaintenanceType.MaintenanceTypeID equals r.MaintenanceTypeID into joinedMaintenanceType
                         from maintenance in joinedMaintenanceType.DefaultIfEmpty()
                         orderby m.MaintenanceType.Name, m.MaintenanceType.Priority
                         select new CombinedMaintenanceType
                         {
                             MaintenanceType = m.MaintenanceType,
                             MaintenaceRecord = m.MaintenaceRecord,
                             IsRecord = m.IsRecord,
                             ServiceMileage = m.ServiceMileage,
                             ServicePeriod = m.ServicePeriod,
                             IsHistory = maintenance != null ? true : false,
                         };
                           
                         

            return from m in query2
                   where m.MaintenaceRecord == null  || (m.MaintenaceRecord != null && m.MaintenaceRecord.IsActive == true)
                   select m;

            
        }
        public IQueryable<MaintenanceType> GetMaintenanceTypeByVehicle(Vehicle vehicle)
        {
                return from m in ccf20Entities.MaintenanceTypes
                        where m.VehicleTypeID == vehicle.VehicleTypeID
                        orderby m.Name,m.Priority        
                        select m;
        }
       
        public void AddDefaultMaintenanceToVehicle(Vehicle vehicle)
        {
            Vehicle myVehicle = ccf20Entities.Vehicles.Where(
                                v => v.VehicleID == vehicle.VehicleID)
                                .FirstOrDefault();
            
            //对所有车辆，更换机油是缺省的保养项目
            VehicleMaintenanceRecord vmr = myVehicle.VehicleMaintenanceRecords.Where(
                                            m => m.MaintenanceType.Name.Contains("更换发动机机油"))
                                            .FirstOrDefault();
            if (vmr == null)
            {
                MaintenanceType mt = ccf20Entities.MaintenanceTypes.Where(
                                        m => m.VehicleTypeID == vehicle.VehicleTypeID
                                          && m.Name.Contains("更换发动机机油"))
                                          .FirstOrDefault();
                if (mt == null) return;
                vmr = new VehicleMaintenanceRecord();
                vmr.MaintenanceType = mt;
                vmr.ServiceMileage = mt.ServiceMileage;
                vmr.ServicePeriod = mt.ServicePeriod;
                //vmr.LastServiceDate = vehicle.LastServcieDate;
                //vmr.LastServiceMileage = vehicle.LastServiceMileage;
                myVehicle.VehicleMaintenanceRecords.Add(vmr);
                ccf20Entities.SaveChanges();
            }

        }
        public int GetMaxID(string tableName)
        {
            int? temp;
            switch (tableName)
            {
                case "VehicleType":
                    temp = ccf20Entities.VehicleTypes.Max(v => v.AnchiID);
                    break;
                    
                case "MaintenanceType":
                    temp = ccf20Entities.MaintenanceTypes.Max(v => v.AnchiID);
                    break;
                default:
                    throw new Exception("Unknow table for GetMaxID");
            }
            return (temp == null) ? 0 : (int)temp;
            

        }
        public int GetMaxVehicleTypeID()
        {
            return GetMaxID("VehicleType");

        }
        public int GetMaxMaintenanceTypeID()
        {
            return GetMaxID("MaintenanceType");

        }
        public void UpdateVehicleType(VehicleType vt)
        {
            VehicleType vehicleType = ccf20Entities.VehicleTypes.Where(v => v.AnchiID == vt.AnchiID).FirstOrDefault();
            if (vehicleType == null)
            {
                vehicleType = ccf20Entities.VehicleTypes.Where(
                                                                 v => v.Manufacture == vt.Manufacture
                                                                   && v.Model == vt.Model
                                                                   && v.EngineType == vt.EngineType
                                                                   && v.Displacement == vt.Displacement)
                                                        .FirstOrDefault();

                if (vehicleType == null)
                {
                    //new vehicletype
                    ccf20Entities.VehicleTypes.AddObject(vt);
                }
                else
                {
                    //same vehicletype existing, but missing anchiid
                    vehicleType.AnchiID = vt.AnchiID;
                }

            }
            else
            {
                //the anchiid existing, so update other info
                vehicleType.Model = vt.Model;
                vehicleType.Manufacture = vt.Manufacture;
                vehicleType.EngineType = vt.EngineType;
            }

        }
        public void UpdateMaintenanceType(MaintenanceType mt)
        {
            //you need to find the vehicle type first before add maintenance
            VehicleType vt = ccf20Entities.VehicleTypes.Where(v => v.AnchiID == mt.VehicleTypeID).FirstOrDefault();
            if (vt == null)
            {
                LoggerHelper.LogCCF20(string.Format("[GetMaintenanceType] 保养项目={0}中车型ID={1} 不为空但无法在车型表里找到", mt.Name, mt.VehicleTypeID));
                return;
            }
            int? vehicleTypeID = vt.VehicleTypeID;
            MaintenanceType maintenanceType = ccf20Entities.MaintenanceTypes.Where(v => v.AnchiID == mt.AnchiID).FirstOrDefault();
            if (maintenanceType == null)
            {
                maintenanceType = ccf20Entities.MaintenanceTypes.Where(m => m.TyID == mt.TyID&& m.Name == mt.Name).FirstOrDefault();

                if (maintenanceType == null)
                {
                    mt.VehicleTypeID = vehicleTypeID;
                    ccf20Entities.MaintenanceTypes.AddObject(mt);
                }
                else
                {
                    //same maintenancetype existing, but missing anchiid
                    maintenanceType.AnchiID = mt.AnchiID;
                }

            }
            else
            {
                //the anchiid existing, so update other info
                maintenanceType.ServicePeriod = mt.ServicePeriod;
                maintenanceType.ServiceMileage = mt.ServiceMileage;
                maintenanceType.Name = mt.Name;
            }

        }
        public bool IsDuplicate(int? vehicleId, int maintenanceTypeId,int? priority)
        {
            if (ccf20Entities.VehicleMaintenanceRecords.Count(
                        m => m.VehicleID == vehicleId && 
                             m.MaintenanceTypeID == maintenanceTypeId &&
                             m.Priority == priority)> 0)
            {
                return true;
            }
            else
            {
                return false;
            }


        }
    }
}